﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.Entity;
using System.Data.Entity.ModelConfiguration.Conventions;
using stackFluent.Domain;

namespace stackFluent.EF {
    public class EFContext : DbContext {

        public EFContext()
            : base("stackFluent") {
            Database.SetInitializer<EFContext>(new EFContextInitializer());
        }

        public DbSet<Category> Categories { get; set; }
        public DbSet<Tech> Techs { get; set; }
        public DbSet<Site> Sites { get; set; }
        public DbSet<User> Users { get; set; }
        public DbSet<RelaSiteSite> RelaSiteSites { get; set; }
        public DbSet<RelaTechSite> RelaTechSites { get; set; }
        public DbSet<RelaTechTech> RelaTechTechs { get; set; }
        public DbSet<RelaUserSite> RelaUserSites { get; set; }
        public DbSet<RelaUserTech> RelaUserTechs { get; set; }
        public DbSet<RelaUserUser> RelaUserUser { get; set; }

        public DbSet<Question> Questions { get; set; }
        public DbSet<Answer> Answers { get; set; }
        public DbSet<Chat> Chats { get; set; }
        public DbSet<Resource> Resources { get; set; }
        public DbSet<Reply> Replys { get; set; }

        public DbSet<Tag> Tags { get; set; }
        public DbSet<RelaTagTag> RelaTagTags { get; set; }
        public DbSet<TagNode> TagNodes { get; set; }
        public DbSet<TagPost> TagPosts { get; set; }

        public DbSet<Vote> Votes { get; set; }

        protected override void OnModelCreating(DbModelBuilder modelBuilder) {
            modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();

            modelBuilder.Entity<RelaTechTech>()
                .HasRequired(x => x.Tech).WithMany(x => x.DependentTechs).HasForeignKey(x => x.Tech_TechId);
            modelBuilder.Entity<RelaTechTech>()
                .HasOptional(x => x.TechTo).WithMany(x => x.BeDependentTechs).HasForeignKey(x => x.TechTo_TechId);

            modelBuilder.Entity<RelaUserUser>()
                .HasRequired(x => x.User).WithMany(x => x.InterUsers).HasForeignKey(x => x.User_UserId);
            modelBuilder.Entity<RelaUserUser>()
                .HasOptional(x => x.UserTo).WithMany(x => x.BeInterUsers).HasForeignKey(x => x.UserTo_UserId);

            //RelaUserSite和RelaUserTech可以使用双主键，但为了今后nosql应用和数据挖掘方便，所以不使用双主键
            //没有反向关系，只有相互关系的RelaTagTag/RelaSiteSite表可以使用双主键，不影响数据挖掘和nosql应用
            modelBuilder.Entity<RelaTagTag>().HasKey(d => new { d.TagId1, d.TagId2 });
            modelBuilder.Entity<RelaSiteSite>().HasKey(d => new { d.Site1Id, d.Site2Id });
        }

    }
}
